package cn.edu.nyist.controller;


import cn.edu.nyist.entity.*;
import cn.edu.nyist.service.RegionService;
import cn.edu.nyist.service.SellHouseService;
import cn.edu.nyist.service.UserSellInfoService;
import cn.edu.nyist.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (SellHouse)表控制层
 *
 * @author cgq
 * @since 2021-03-21 17:55:12
 */
@Controller
@RequestMapping("sellHouse")
public class SellHouseController {

    @Value("${img.location.sellHouse}")
    private String folder;

    private static Logger log = LoggerFactory.getLogger(SellHouseController.class);

    @Autowired
    private AjaxResult ajaxResult;

    @Autowired
    private SellHouseService sellHouseService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private UserSellInfoService userSellInfoService;

    @GetMapping("/house")
    public String house(HttpSession session){

        List<Region> regions = regionService.queryAllRegion();
        session.setAttribute(Const.REGIONLIST,regions);
        return "yju/sellHouse/sellHouseList";
    }


    @RequestMapping("/sellHouseIndexList")
    @ResponseBody
    //房屋的标题，房屋类型，价格最小值，价格最大值、面积最小值、面积最大值、户型，地区，装修情况，朝向,房本年限说明，产权,楼层
    //南北通透、唯一住房、电梯
    public Object sellHouseIndexList(@RequestParam(defaultValue = "1") Integer pageno,
                                @RequestParam( defaultValue = "6") Integer pagesize,
                                String title, String type, Double minPrice ,Double maxPrice ,
                                Double minArea ,Double maxArea, String houseType, String region,
                                String decoration, String orientation, String premisesPermitAge, String nature,
                                String floorLevel,Integer northSouth ,Integer onlyHousing  ,Integer lift){

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("pageno",pageno);
        paramMap.put("pagesize",pagesize);

        //判断是否为空
        if(!StringUtils.isEmpty(title)) {
            log.info("title:"+title);
            paramMap.put("title",title);
        }
        if(!StringUtils.isEmpty(houseType)) {
            log.info("houseType:"+houseType);
            paramMap.put("houseType",houseType);
        }
        if(!StringUtils.isEmpty(type)) {
            log.info("type:"+type);
            paramMap.put("type",type);
        }
        if(!StringUtils.isEmpty(region)) {
            log.info("region:"+region);
            paramMap.put("region",region);
        }
        if(!StringUtils.isEmpty(floorLevel)) {
            log.info("floorLevel:"+floorLevel);
            paramMap.put("floorLevel",floorLevel);
        }
        if( minPrice != null ) {
            log.info("minPrice:"+minPrice);
            paramMap.put("minPrice",minPrice);
        }
        if( maxPrice != null ) {
            log.info("maxPrice:"+maxPrice);
            paramMap.put("maxPrice",maxPrice);
        }
        if( minArea != null ) {
            log.info("minArea:"+minArea);
            paramMap.put("minArea",minArea);
        }
        if( maxArea != null ) {
            log.info("maxArea:"+maxArea);
            paramMap.put("maxArea",maxArea);
        }
        if(!StringUtils.isEmpty(decoration)) {
            log.info("decoration:"+decoration);
            paramMap.put("decoration",decoration);
        }
        if(!StringUtils.isEmpty(orientation)) {
            log.info("orientation:"+orientation);
            paramMap.put("orientation",orientation);
        }

        if(!StringUtils.isEmpty(premisesPermitAge)) {
            log.info("premisesPermitAge:"+premisesPermitAge);
            paramMap.put("premisesPermitAge",premisesPermitAge);
        }

        if(!StringUtils.isEmpty(nature)) {
            log.info("nature:"+nature);
            paramMap.put("nature",nature);
        }
        if( lift != null ) {
            log.info("lift:"+lift);
            paramMap.put("lift",lift);
        }
        if( onlyHousing  !=null ) {
            log.info("onlyHousing:"+onlyHousing);
            paramMap.put("onlyHousing",onlyHousing);
        }
        if(northSouth !=null) {
            log.info("northSouth:" + northSouth);
            paramMap.put("northSouth", northSouth);
        }

        PageBean<SellHouse> pageBean = sellHouseService.queryPage(paramMap);
        Map<String,Object> rest = new HashMap();
//        rest.put("code", 0);
//        rest.put("msg", "");
        //总条数
        rest.put("count",pageBean.getTotalsize());
        //当前页
        rest.put("pageno",pageBean.getPageno());
        //总页数
        rest.put("totalno",pageBean.getTotalno());
        rest.put("data", pageBean.getDatas());
        return rest;
    }

    //BelongUser
    @RequestMapping("/sellHouseListBelongUser")
    @ResponseBody
    public Object sellHouseListBelongUser(@RequestParam(value = "page", defaultValue = "1") Integer pageno,
                                @RequestParam(value = "limit", defaultValue = "5") Integer pagesize,
                              HttpSession session){

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("pageno",pageno);
        paramMap.put("pagesize",pagesize);


        CommonUser commonUser = (CommonUser) session.getAttribute(Const.COMMONUSER);
        paramMap.put("userId",commonUser.getId());

        PageBean<SellHouse> pageBean = sellHouseService.queryPageBelongUser(paramMap);
        Map<String,Object> rest = new HashMap();
        rest.put("code", 0);
        rest.put("msg", "");
        rest.put("count",pageBean.getTotalsize());
        rest.put("data", pageBean.getDatas());
        return rest;
    }


    @RequestMapping("/sellHouseIndexListAreaDesc")
    @ResponseBody
    //房屋的标题，房屋类型，价格最小值，价格最大值、面积最小值、面积最大值、户型，地区，装修情况，朝向,房本年限说明，产权,楼层
    //南北通透、唯一住房、电梯
    public Object sellHouseIndexListAreaDesc(@RequestParam(defaultValue = "1") Integer pageno,
                                     @RequestParam( defaultValue = "6") Integer pagesize,
                                     String title, String type, Double minPrice ,Double maxPrice ,
                                     Double minArea ,Double maxArea, String houseType, String region,
                                     String decoration, String orientation, String premisesPermitAge, String nature,
                                     String floorLevel,Integer northSouth ,Integer onlyHousing  ,Integer lift){

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("pageno",pageno);
        paramMap.put("pagesize",pagesize);

        //判断是否为空
        if(!StringUtils.isEmpty(title)) {
            log.info("title:"+title);
            paramMap.put("title",title);
        }
        if(!StringUtils.isEmpty(houseType)) {
            log.info("houseType:"+houseType);
            paramMap.put("houseType",houseType);
        }
        if(!StringUtils.isEmpty(type)) {
            log.info("type:"+type);
            paramMap.put("type",type);
        }
        if(!StringUtils.isEmpty(region)) {
            log.info("region:"+region);
            paramMap.put("region",region);
        }
        if(!StringUtils.isEmpty(floorLevel)) {
            log.info("floorLevel:"+floorLevel);
            paramMap.put("floorLevel",floorLevel);
        }
        if( minPrice != null ) {
            log.info("minPrice:"+minPrice);
            paramMap.put("minPrice",minPrice);
        }
        if( maxPrice != null ) {
            log.info("maxPrice:"+maxPrice);
            paramMap.put("maxPrice",maxPrice);
        }
        if( minArea != null ) {
            log.info("minArea:"+minArea);
            paramMap.put("minArea",minArea);
        }
        if( maxArea != null ) {
            log.info("maxArea:"+maxArea);
            paramMap.put("maxArea",maxArea);
        }
        if(!StringUtils.isEmpty(decoration)) {
            log.info("decoration:"+decoration);
            paramMap.put("decoration",decoration);
        }
        if(!StringUtils.isEmpty(orientation)) {
            log.info("orientation:"+orientation);
            paramMap.put("orientation",orientation);
        }

        if(!StringUtils.isEmpty(premisesPermitAge)) {
            log.info("premisesPermitAge:"+premisesPermitAge);
            paramMap.put("premisesPermitAge",premisesPermitAge);
        }

        if(!StringUtils.isEmpty(nature)) {
            log.info("nature:"+nature);
            paramMap.put("nature",nature);
        }
        if( lift != null ) {
            log.info("lift:"+lift);
            paramMap.put("lift",lift);
        }
        if( onlyHousing  !=null ) {
            log.info("onlyHousing:"+onlyHousing);
            paramMap.put("onlyHousing",onlyHousing);
        }
        if(northSouth !=null) {
            log.info("northSouth:" + northSouth);
            paramMap.put("northSouth", northSouth);
        }

        PageBean<SellHouse> pageBean = sellHouseService.queryPageAreaDesc(paramMap);
        Map<String,Object> rest = new HashMap();
        //总条数
        rest.put("count",pageBean.getTotalsize());
        //当前页
        rest.put("pageno",pageBean.getPageno());
        //总页数
        rest.put("totalno",pageBean.getTotalno());
        rest.put("data", pageBean.getDatas());
        return rest;
    }




    @RequestMapping("/sellHouseIndexListPriceAsc")
    @ResponseBody
    //房屋的标题，房屋类型，价格最小值，价格最大值、面积最小值、面积最大值、户型，地区，装修情况，朝向,房本年限说明，产权,楼层
    //南北通透、唯一住房、电梯
    public Object sellHouseIndexListPriceAsc(@RequestParam(defaultValue = "1") Integer pageno,
                                     @RequestParam( defaultValue = "6") Integer pagesize,
                                     String title, String type, Double minPrice ,Double maxPrice ,
                                     Double minArea ,Double maxArea, String houseType, String region,
                                     String decoration, String orientation, String premisesPermitAge, String nature,
                                     String floorLevel,Integer northSouth ,Integer onlyHousing  ,Integer lift){

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("pageno",pageno);
        paramMap.put("pagesize",pagesize);

        //判断是否为空
        if(!StringUtils.isEmpty(title)) {
            log.info("title:"+title);
            paramMap.put("title",title);
        }
        if(!StringUtils.isEmpty(houseType)) {
            log.info("houseType:"+houseType);
            paramMap.put("houseType",houseType);
        }
        if(!StringUtils.isEmpty(type)) {
            log.info("type:"+type);
            paramMap.put("type",type);
        }
        if(!StringUtils.isEmpty(region)) {
            log.info("region:"+region);
            paramMap.put("region",region);
        }
        if(!StringUtils.isEmpty(floorLevel)) {
            log.info("floorLevel:"+floorLevel);
            paramMap.put("floorLevel",floorLevel);
        }
        if( minPrice != null ) {
            log.info("minPrice:"+minPrice);
            paramMap.put("minPrice",minPrice);
        }
        if( maxPrice != null ) {
            log.info("maxPrice:"+maxPrice);
            paramMap.put("maxPrice",maxPrice);
        }
        if( minArea != null ) {
            log.info("minArea:"+minArea);
            paramMap.put("minArea",minArea);
        }
        if( maxArea != null ) {
            log.info("maxArea:"+maxArea);
            paramMap.put("maxArea",maxArea);
        }
        if(!StringUtils.isEmpty(decoration)) {
            log.info("decoration:"+decoration);
            paramMap.put("decoration",decoration);
        }
        if(!StringUtils.isEmpty(orientation)) {
            log.info("orientation:"+orientation);
            paramMap.put("orientation",orientation);
        }

        if(!StringUtils.isEmpty(premisesPermitAge)) {
            log.info("premisesPermitAge:"+premisesPermitAge);
            paramMap.put("premisesPermitAge",premisesPermitAge);
        }

        if(!StringUtils.isEmpty(nature)) {
            log.info("nature:"+nature);
            paramMap.put("nature",nature);
        }
        if( lift != null ) {
            log.info("lift:"+lift);
            paramMap.put("lift",lift);
        }
        if( onlyHousing  !=null ) {
            log.info("onlyHousing:"+onlyHousing);
            paramMap.put("onlyHousing",onlyHousing);
        }
        if(northSouth !=null) {
            log.info("northSouth:" + northSouth);
            paramMap.put("northSouth", northSouth);
        }

        PageBean<SellHouse> pageBean = sellHouseService.queryPagePriceAsc(paramMap);
        Map<String,Object> rest = new HashMap();
        //总条数
        rest.put("count",pageBean.getTotalsize());
        //当前页
        rest.put("pageno",pageBean.getPageno());
        //总页数
        rest.put("totalno",pageBean.getTotalno());
        rest.put("data", pageBean.getDatas());
        return rest;
    }

    @RequestMapping("/sellHouseList")
    @ResponseBody
    //房屋的标题，房屋类型，户型，地区，小区，装修情况，朝向,产权,楼层
    public Object sellHouseList(@RequestParam(value = "page", defaultValue = "1") Integer pageno,
                                @RequestParam(value = "limit", defaultValue = "5") Integer pagesize,
                                String title, String type, String houseType, String region,
                                String housingEstate , String decoration, String orientation, String nature,String floorLevel){

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("pageno",pageno);
        paramMap.put("pagesize",pagesize);

        //判断是否为空
        if(!StringUtils.isEmpty(title)) {
            log.info("title:"+title);
            paramMap.put("title",title);
        }
        if(!StringUtils.isEmpty(houseType)) {
            log.info("houseType:"+houseType);
            paramMap.put("houseType",houseType);
        }
        if(!StringUtils.isEmpty(type)) {
            log.info("type:"+type);
            paramMap.put("type",type);
        }
        if(!StringUtils.isEmpty(region)) {
            log.info("region:"+region);
            paramMap.put("region",region);
        }
        if(!StringUtils.isEmpty(housingEstate)) {
            log.info("housingEstate:"+housingEstate);
            paramMap.put("housingEstate",housingEstate);
        }
        if(!StringUtils.isEmpty(decoration)) {
            log.info("decoration:"+decoration);
            paramMap.put("decoration",decoration);
        }
        if(!StringUtils.isEmpty(orientation)) {
            log.info("orientation:"+orientation);
            paramMap.put("orientation",orientation);
        }

        if(!StringUtils.isEmpty(nature)) {
            log.info("nature:"+nature);
            paramMap.put("nature",nature);
        }

        if(!StringUtils.isEmpty(floorLevel)) {
            log.info("floorLevel:"+floorLevel);
            paramMap.put("floorLevel",floorLevel);
        }

        PageBean<SellHouse> pageBean = sellHouseService.queryPage(paramMap);
        Map<String,Object> rest = new HashMap();
        rest.put("code", 0);
        rest.put("msg", "");
        rest.put("count",pageBean.getTotalsize());
        rest.put("data", pageBean.getDatas());
        return rest;
    }


    /**
     * 跳转添加卖房信息页面
     * @return
     */
    @GetMapping("/addSellHouse")
    public String addSellHouse(String type, Integer id, Model model){
        if(type != null && type.equals("edit")){
            SellHouse  sellHouse = sellHouseService.selectById(id);
            model.addAttribute(Const.SELLHOUSE,sellHouse);
            model.addAttribute(Const.SELLHOUSEIMGS,sellHouse.getPicture());
        }
        return "yju/sellHouse/addSellHouse";
    }

    /**
     * 根据id查询租房信息
     * @param id
     * @return
     */
    @RequestMapping("querySellHouseById")
    @ResponseBody
    public SellHouse querySellHouseById(Integer id){

        return  sellHouseService.selectById(id);

    }


    /**
     *查看详细信息
     */
    @GetMapping("detailSellHouse")
    public String detailSellHouse(Integer id, Model model){
        SellHouse sellHouse = sellHouseService.selectById(id);
        model.addAttribute(Const.SELLHOUSE,sellHouse);
        return "yju/sellHouse/detailSellHouse";
    }

    /**
     * 添加地区  修改地区
     * @param sellHouse
     * @return
     */
    @PostMapping("/addSellHouse")
    @ResponseBody
    public AjaxResult submitAddSellHouse(SellHouse sellHouse,HttpSession session){

        log.info("sellHouse:"+sellHouse);
        if(sellHouse.getId() !=null){

            String sellHouseImgs = (String) session.getAttribute(Const.SELLHOUSEIMGS);
            if ( sellHouseImgs !=null && StringUtils.isEmpty(sellHouse.getPicture())){
                sellHouse.setPicture(sellHouseImgs);
            }
            int count = sellHouseService.editBySellHouse(sellHouse);
            if(count > 0){
                ajaxResult.ajaxTrue("修改成功");
            }else{
                ajaxResult.ajaxFalse("修改失败");
            }
        }else {
            String sellHouseImgs = (String) session.getAttribute(Const.SELLHOUSEIMGS);
            if (sellHouseImgs == null) {
                ajaxResult.ajaxFalse("图片不能为空！");
            } else {
                sellHouse.setPicture(sellHouseImgs);
                String publishTime = DateUtil.getStringDate("yyyy-MM-dd");
                sellHouse.setPublishTime(publishTime);
                int count = sellHouseService.insertSellHouse(sellHouse);
                if (count > 0) {
                    //判断是否是普通用户添加
                    if(!StringUtils.isEmpty(session.getAttribute(Const.USERADDSELLHOUSE))
                            && "yes".equals(session.getAttribute(Const.USERADDSELLHOUSE))){
                        log.info("rentHouseId:"+sellHouse.getId());
                        CommonUser user = (CommonUser) session.getAttribute(Const.COMMONUSER);
                        // 创建userRentInfo 对象
                        UserSellInfo userSellInfo = new UserSellInfo(user.getId(),sellHouse.getId());
                        Integer rentCount = userSellInfoService.insert(userSellInfo);
                        if (rentCount >0){
                            ajaxResult.ajaxTrue("添加成功");
                        }else{
                            ajaxResult.ajaxFalse("添加失败");
                        }
                    }else {
                        ajaxResult.ajaxTrue("添加成功");
                        session.removeAttribute(Const.USERADDSELLHOUSE);
                    }
                } else {
                    ajaxResult.ajaxFalse("添加失败");
                }
            }
        }
        return ajaxResult;
    }

    /**
     * 删除卖房信息
     * @param data
     * @return
     */
    @PostMapping("/delSellHouse")
    @ResponseBody
    public AjaxResult delSellHouse(Data data,HttpSession session){

        for (Integer id : data.getIds()) {
            SellHouse sellHouse = sellHouseService.selectById(id);
            String picture = sellHouse.getPicture();
            log.info("picture: "+picture);
            //删除图片
            deleteImg(picture);
        }

        if(!StringUtils.isEmpty(session.getAttribute(Const.USERSELLHOUSEINFOLIST))
                && "yes".equals(session.getAttribute(Const.USERSELLHOUSEINFOLIST))){

            CommonUser commonUser = (CommonUser) session.getAttribute(Const.COMMONUSER);
            List<Integer> ids = data.getIds();
            log.info("-------------------------");
            log.info("ids:"+ids.toArray());
            log.info("userId:"+commonUser.getId());
            log.info("-------------------------");

            Map<String,Object> map = new HashMap<>();
            map.put("userId",commonUser.getId());
            map.put("ids",ids);
            //删除 user_sell_info
            int i = userSellInfoService.deleteByUserId(map);
            if( i >= 1 ){
                log.info("user_sell_info表中记录删除成功！");
            }
        }

        int count = sellHouseService.delBySellHouseIds(data.getIds());
        log.info("count:"+count);
        if(count >= data.getIds().size()){
            ajaxResult.ajaxTrue("删除成功");
            log.info("删除成功！");
            session.removeAttribute(Const.USERSELLHOUSEINFOLIST);
        }else{
            ajaxResult.ajaxFalse("删除失败");
            log.info("删除失败！");
        }
        return ajaxResult;
    }

    /**
     * 清除session中的 sellHouseImgs 属性
     *
     */
    @RequestMapping("/removeSeesionValue")
    @ResponseBody
    public AjaxResult removeSeesionValue(HttpSession session){
        String sellHouseImgs = (String) session.getAttribute(Const.SELLHOUSEIMGS);
        log.info("sellHouseImgs: "+sellHouseImgs);
        //删除图片
        deleteImg(sellHouseImgs);
        session.removeAttribute(Const.SELLHOUSEIMGS);
        sellHouseImgs = (String) session.getAttribute(Const.SELLHOUSEIMGS);
        if (StringUtils.isEmpty(sellHouseImgs)){
            ajaxResult.ajaxTrue("重置成功！");
        }else{
            ajaxResult.ajaxFalse("重置失败！");
        }
        return ajaxResult;

    }

    /**
     * 上传图片
     *
     */
    @PostMapping("/uploadImgs")
    @ResponseBody
    public AjaxResult uploadImgs(HttpServletRequest request, @RequestParam(value = "imgs", required = false) MultipartFile[] multipartImgs) throws IOException {
        log.info("上传图片");
        HttpSession session = request.getSession();
        StringBuffer sellHouseImgs =  new StringBuffer();
        try{

            for (int i=0;i<multipartImgs.length;i++) {
                MultipartFile img=multipartImgs[i];
                String fileName = img.getOriginalFilename();
                //文件名后缀
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String newFileName = System.currentTimeMillis() + "." + suffix;

                if(i == multipartImgs.length-1){
                    sellHouseImgs.append(newFileName);
                }
                else {
                    sellHouseImgs.append(newFileName+",");
                }
                log.info(folder+ newFileName);
                File localFile = new File(folder, newFileName);
                img.transferTo(localFile);
                log.info("http://localhost:8099"+"/upload/sellHouse/"+newFileName);
            }
            log.info(sellHouseImgs.toString());
            session.setAttribute(Const.SELLHOUSEIMGS,sellHouseImgs.toString());
            ajaxResult.ajaxTrue("图片上传成功！");

        }catch (Exception e){
            ajaxResult.ajaxFalse("图片上传失败！");
        }
        return ajaxResult;
    }

    public void deleteImg(String sellHouseImgs){
        if (!StringUtils.isEmpty(sellHouseImgs)){
            String[] imgs = sellHouseImgs.split(",");
            for (String img : imgs) {
                String filePath = folder+img;
                log.info("filePath"+filePath);
                File file = new File(filePath);
                boolean delete = file.delete();
                log.info("图片删除情况："+delete);
            }
        }
    }
}